package com.razorthink.shell.core;

import java.io.BufferedReader;
import java.io.Console;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import com.razorthink.shell.utils.CommandLogger;

public class ShellIO {

	public static String read(String prompt) throws IOException {
		System.out.print(prompt);
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String readString = null;
		try {
			readString = br.readLine();
		} catch (IOException ioe) {
			CommandLogger.logInfo("IO error. Terminating...");
			System.exit(1);
		}
		if (readString == null) {
			CommandLogger
					.logInfo("Recieved termination signal. Terminating...");
			System.exit(1);
		}
		String transformed = formatString(readString);
		return (transformed);
	}

	public static String formatString(String str) {
		return str.replace("\\\\", "\\").replace("\\N", "\\\\N")
				.replace("\\T", "\\\\T").replace("\\B", "\\\\B")
				.replace("\\F", "\\\\F").replace("\\R", "\\\\R")
				.replace("\\U", "\\\\U").replace("\\u", "\\\\u")
				.replace("\\i", "\\\\i").replace("\\p", "\\\\p'")
				.replace("\\'", "\\\\'");
	}

	public static String maskedRead(String prompt) {
		if (!isConsoleCompatible()) {
			return "";
		}
		Console cons = System.console();
		char[] read = null;
		String password = "";
		if ((read = cons.readPassword("%s", prompt)) != null) {
			for (char c : read) {
				password += c;
			}
		}
		return password;
	}

	public static boolean isConsoleCompatible() {
		if (System.console() == null) {
			return false;
		}
		return true;
	}

	// public static String maskRead(String prompt) throws IOException {
	// System.out.print(prompt);
	// return new jline.ConsoleReader().readLine(new Character('*'));
	// }

	/**
	 * @see <a
	 *      href="http://www.esus.com/docs/GetQuestionPage.jsp?uid=392">Shutdown
	 *      app by trapping ^C</a>
	 */
	public static void shutdown() {
		// Runtime.getRuntime().addShutdownHook(new Thread());
	}

	public static String readFileContents(String fileName) throws IOException {
		BufferedReader in = null;
		String ret = "";
		String str = "";
		try {
			in = new BufferedReader(new FileReader(fileName));
			while ((str = in.readLine()) != null) {
				ret += str + "\n";
			}
			in.close();
		} catch (FileNotFoundException e) {
			CommandLogger.logError(e);
		}
		return ret;
	}

	public static void appendFile(File file, String content) throws IOException {
		if (file.exists()) {
			String filecontent = readFileContents(file.getAbsolutePath())
					+ "\n" + content;
			content = filecontent;
		} else {
			file.createNewFile();
		}
		PrintWriter out = new PrintWriter(new FileWriter(file), true);
		out.print(content);
		out.flush();
		out.close();
	}
}